package com.fhc.view

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MenuAnchorType
import androidx.compose.material3.MenuDefaults
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.PopupProperties
import timber.log.Timber
import kotlin.math.ceil

data class NameValueDto(val name: String, val value: String)

val items = List(30) { index ->
    NameValueDto("选项${index + 1}", "value${index + 1}")
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DropdownBox(modifier: Modifier = Modifier, items: List<NameValueDto>, selectedItem:NameValueDto = NameValueDto("",""),
                itemHeight: Dp =  48.dp, maxVisibleItems:Int = 5, noValueStr:String = "--",
                onValueChange: (NameValueDto) -> Unit,) {
    var expanded by remember { mutableStateOf(false) }
    var selectedValue by remember { mutableStateOf(selectedItem) }
    val scrollState = rememberScrollState()
    var itemHeightPx = 48f
    with(LocalDensity.current){
        itemHeightPx = itemHeight.toPx()
    }

    val visibleItemCount = if(items.size > maxVisibleItems) maxVisibleItems else items.size // 可视区域显示项数

    LaunchedEffect(expanded) {
        if (expanded) {
            val selectedIndex = items.indexOfFirst { it == selectedValue }
            if (selectedIndex >= ceil(visibleItemCount/2.0)) {
                //偏移targetPosition*itemHeightPx 使选择项在最上； 如果选择项居中，则再往回偏移 【可视区域显示项数 -1】 的一半高度
                val targetPosition = selectedIndex * itemHeightPx -  (visibleItemCount-1) / 2.0 * itemHeightPx
                //最大scroll为 item数-visibleItemCount * itemHeight
//                scrollState.animateScrollTo(targetPosition.toInt().coerceIn(0, (items.size  -  visibleItemCount) * itemHeightPx.toInt()))
                scrollState.scrollTo(targetPosition.toInt().coerceIn(0, (items.size  -  visibleItemCount) * itemHeightPx.toInt()))
                Timber.e("selectedIndex: ${(selectedIndex  - visibleItemCount / 2.0)}  targetPosition: ${itemHeightPx}  ")
            }
        }
    }

    Box(modifier = modifier) {
        ExposedDropdownMenuBox(
            expanded = expanded,
            onExpandedChange = { expanded = !expanded }
        ) {
            TextField(
                value = selectedValue.name.ifEmpty { noValueStr },
                onValueChange = {},
                readOnly = true,
                trailingIcon = {
                    ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded)
                },
                // 新版标准用法
                modifier = Modifier.menuAnchor(
                    type = MenuAnchorType.PrimaryNotEditable,
                    enabled = true
                )
            )

            ExposedDropdownMenu(
                expanded = expanded,
                onDismissRequest = { expanded = false }
            ) {
                Box(modifier = Modifier.height(itemHeight * visibleItemCount)) {
                    Column(Modifier.verticalScroll(scrollState)) {
                        items.forEach { item ->
                            DropdownMenuItem(
                                modifier = Modifier.height(itemHeight),
                                text = {
                                    Row(verticalAlignment = Alignment.CenterVertically) {
                                        if (selectedValue == item) {
                                            Icon(
                                                imageVector = Icons.Default.Check,
                                                contentDescription = "已选中",
                                                modifier = Modifier.size(16.dp)
                                            )
                                            Spacer(modifier = Modifier.width(8.dp))
                                        }
                                        Text(text = item.name)
                                    }
                                },
                                onClick = {
                                    selectedValue = item
                                    onValueChange(selectedValue)
                                    expanded = false
                                }
                            )
                        }
                    }
                }
            }
        }
    }
}



@Composable
fun MoreTasksMenu(
    onSetting: () -> Unit,
    onRefresh: () -> Unit
) {
    var isItem1Selected by remember { mutableStateOf(false) }
    var isItem2Selected by remember { mutableStateOf(false) }
    TopAppBarDropdownMenu(
        iconContent = {
            Icon(Icons.Filled.MoreVert, null)
        }
    ) { closeMenu ->
        DropdownMenuItem(
            modifier = Modifier.wrapContentSize(),
            onClick = {
                isItem1Selected = !isItem1Selected
                onSetting()
                closeMenu()
            },
            text = {Text(text = "Settings")},
            leadingIcon = {Icon(
                imageVector = Icons.Default.Settings,
                contentDescription = null,
                tint = Color.Blue
            )},
            trailingIcon = {if(isItem1Selected){
                Icon(
                    modifier = Modifier.size(20.dp),
                    imageVector = Icons.Default.Check,
                    contentDescription = null,
                    tint = Color.Blue
                )
            }else{
                Box(
                    modifier = Modifier.size(20.dp).background(Color.Red)
                )
            }},
            contentPadding = MenuDefaults.DropdownMenuItemContentPadding,
        )

        DropdownMenuItem(
            modifier = Modifier.wrapContentSize(),
            onClick = {
                isItem2Selected = !isItem2Selected
                onRefresh()
                closeMenu()
            },
            text = {Text(text ="refresh")},
            leadingIcon = {Icon(
                imageVector = Icons.Default.Refresh,
                contentDescription = null,
                tint = Color.Blue
            )},
            trailingIcon = {if(isItem2Selected){
                Icon(
                    modifier = Modifier.size(20.dp),
                    imageVector = Icons.Default.Check,
                    contentDescription = null,
                    tint = Color.Blue
                )
            }else{null}},
        )
    }
}

@Composable
fun TopAppBarDropdownMenu(
    expanded: MutableState<Boolean> = remember { mutableStateOf(false) },
    iconContent: @Composable () -> Unit,
    content: @Composable ColumnScope.(() -> Unit) -> Unit
) {
//    var expanded by remember { mutableStateOf(false) }

    Box(modifier = Modifier.wrapContentSize(Alignment.TopEnd)) {
        IconButton(onClick = { expanded.value = !expanded.value }) {
            iconContent()
        }
        DropdownMenu(
            expanded = expanded.value,
            offset= DpOffset((-10).dp, 10.dp),
            onDismissRequest = { expanded.value = false },
            properties = PopupProperties(dismissOnClickOutside = true),
            modifier = Modifier.wrapContentSize(Alignment.TopEnd)

        ) {
            content { expanded.value = !expanded.value }
        }
    }
}